/**   
 * @Title: PropertiesConfigListener.java 
 * @Package cn.com.gome.frame.listener 
 * @Description:  配置文件加载监听器 
 * @author chenmin-ds   
 * @date 2015年2月27日 上午11:56:29 
 * @company cn.com.gome
 * @version V1.0   
 */

package com.gomeplus.frame.listener;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gomeplus.frame.cache.GlobalApplicationCache;

/**
 * @ClassName: PropertiesConfigListener
 * @Description: 配置文件加载监听器
 * @author chenmin-ds
 * @date 2015年2月27日 上午11:56:29
 */
public class PropertiesConfigListener implements ServletContextListener {

	private Logger logger = LoggerFactory.getLogger("PropertiesConfigListener");

	/** 多个配置文件以“,”号隔开 */
	private String propertiesConfigLocation;

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		try {
			propertiesConfigLocation = sce.getServletContext().getInitParameter("propertiesConfigLocation").trim();
			logger.info("监听器加载配置文件开始，文件名称如下：{}",propertiesConfigLocation);
			if (StringUtils.isNotEmpty(propertiesConfigLocation)) {
				String[] paths = propertiesConfigLocation.split(",");
				InputStream is = null;
				BufferedReader br = null;
				String lineStr = null;
				String key, value;
				int index = 0;
				for (String path : paths) {
					is = this.getClass().getResourceAsStream(path);
					br = new BufferedReader(new InputStreamReader(is));
					while ((lineStr = br.readLine()) != null) {
						if (lineStr.startsWith("#")) {
							continue;
						}
						index = lineStr.indexOf("=");
						if (index <= 0) {
							continue;
						}
						key = lineStr.substring(0, index).trim();
						value = lineStr.substring(index + 1, lineStr.length()).trim();
						logger.debug("##########key=" + key + ",value=" + value);
						GlobalApplicationCache.getInstance().put(key, value);
					}
				}
			}
		} catch (FileNotFoundException e) {
			logger.error("监听器加载配置文件，文件示找到异常" , e);
		} catch (IOException e) {
			logger.error("监听器加载配置文件，读取文件异常" , e);
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
	}
}
